<template>
  <view class="profile-page">
    <!-- 用户信息 -->
    <view class="user-section">
      <view class="avatar-container" @click="changeAvatar">
        <image 
          :src="userInfo.avatarUrl || '/static/icons/default-avatar.png'" 
          class="user-avatar"
          mode="aspectFill"
        />
        <view class="avatar-edit">
          <text>编辑</text>
        </view>
      </view>
      
      <view class="user-info">
        <view class="info-item" @click="editNickname">
          <view class="info-label">昵称</view>
          <view class="info-value">{{ userInfo.nickname || '未设置' }}</view>
          <view class="info-arrow">></view>
        </view>
        
        <view class="info-item" @click="navigateTo('/pages/members/center')">
          <view class="info-label">会员等级</view>
          <view class="info-value">{{ memberLevelText }}</view>
          <view class="info-arrow">></view>
        </view>
        
        <view class="info-item">
          <view class="info-label">手机号</view>
          <view class="info-value">{{ userInfo.phone || '未绑定' }}</view>
          <view class="info-arrow" v-if="!userInfo.phone" @click="bindPhone">></view>
        </view>
        
        <view class="info-item">
          <view class="info-label">注册时间</view>
          <view class="info-value">{{ formatDate(userInfo.createdAt) }}</view>
        </view>
      </view>
    </view>
    
    <!-- 积分信息 -->
    <view class="points-section">
      <view class="section-title">积分信息</view>
      <view class="points-grid">
        <view class="points-item" @click="navigateTo('/pages/points/earn')">
          <view class="points-value">{{ availablePoints }}</view>
          <view class="points-label">可用积分</view>
        </view>
        <view class="points-item" @click="navigateTo('/pages/points/history')">
          <view class="points-value">{{ totalEarned }}</view>
          <view class="points-label">累计获得</view>
        </view>
        <view class="points-item" @click="navigateTo('/pages/points/history?type=consume')">
          <view class="points-value">{{ totalConsumed }}</view>
          <view class="points-label">累计消费</view>
        </view>
      </view>
    </view>
    
    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-item" @click="navigateTo('/pages/orders/list')">
        <view class="menu-icon">📋</view>
        <view class="menu-text">我的订单</view>
        <view class="menu-arrow">></view>
      </view>
      
      <view class="menu-item" @click="navigateTo('/pages/files/list')">
        <view class="menu-icon">📁</view>
        <view class="menu-text">我的文件</view>
        <view class="menu-arrow">></view>
      </view>
      
      <view class="menu-item" @click="navigateTo('/pages/print/list')">
        <view class="menu-icon">🖨️</view>
        <view class="menu-text">打印记录</view>
        <view class="menu-arrow">></view>
      </view>
      
      <view class="menu-item" @click="navigateTo('/pages/invite/index')">
        <view class="menu-icon">👥</view>
        <view class="menu-text">邀请好友</view>
        <view class="menu-arrow">></view>
      </view>
    </view>
    
    <!-- 设置菜单 -->
    <view class="settings-section">
      <view class="menu-item" @click="showAbout">
        <view class="menu-icon">ℹ️</view>
        <view class="menu-text">关于我们</view>
        <view class="menu-arrow">></view>
      </view>
      
      <view class="menu-item" @click="showPrivacy">
        <view class="menu-icon">🔒</view>
        <view class="menu-text">隐私政策</view>
        <view class="menu-arrow">></view>
      </view>
      
      <view class="menu-item" @click="logout">
        <view class="menu-icon">🚪</view>
        <view class="menu-text">退出登录</view>
        <view class="menu-arrow">></view>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo } from '@/api/user.js'
import { getPointsBalance, getPointsStats } from '@/api/points.js'

export default {
  name: 'ProfilePage',
  
  data() {
    return {
      userInfo: {
        nickname: '',
        avatarUrl: '',
        phone: '',
        createdAt: ''
      },
      memberLevelText: '普通会员',
      availablePoints: 0,
      totalEarned: 0,
      totalConsumed: 0
    }
  },
  
  onLoad() {
    this.initStatusBar()
    this.loadUserData()
    this.loadPointsData()
  },
  
  onShow() {
    this.loadUserData()
    this.loadPointsData()
  },
  
  methods: {
    /**
     * 初始化状态栏高度
     */
    initStatusBar() {
      const systemInfo = uni.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight || 0
      
      // 设置CSS变量
      if (typeof document !== 'undefined' && document.documentElement) {
        document.documentElement.style.setProperty('--status-bar-height', statusBarHeight * 2 + 'rpx')
      }
    },
    
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },
    
    /**
     * 加载用户数据
     */
    async loadUserData() {
      try {
        // 先从store获取
        if (this.$store.state.auth && this.$store.state.auth.userInfo) {
          this.userInfo = this.$store.state.auth.userInfo
          this.memberLevelText = this.userInfo.memberLevel || this.userInfo.member_level || '普通会员'
        }
        
        // 再从API获取最新数据
        const result = await getUserInfo()
        if (result && result.success) {
          this.userInfo = result.data
          this.memberLevelText = result.data.memberLevel || result.data.member_level || '普通会员'
          
          // 更新store和缓存
          this.$store.commit('auth/setUserInfo', result.data)
          uni.setStorageSync('userInfo', result.data)
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
        uni.showToast({
          title: '加载用户信息失败',
          icon: 'none'
        })
      }
    },
    
    /**
     * 加载积分数据
     */
    async loadPointsData() {
      try {
        // 获取积分余额
        const balanceResult = await getPointsBalance()
        if (balanceResult && balanceResult.success) {
          this.availablePoints = balanceResult.data.availablePoints || 0
        }
        
        // 获取积分统计
        const statsResult = await getPointsStats()
        if (statsResult && statsResult.success) {
          this.totalEarned = statsResult.data.totalEarned || 0
          this.totalConsumed = statsResult.data.totalConsumed || 0
        }
      } catch (error) {
        console.error('加载积分数据失败:', error)
        uni.showToast({
          title: '加载积分数据失败',
          icon: 'none'
        })
      }
    },
    
    /**
     * 更换头像
     */
    changeAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          this.uploadAvatar(tempFilePath)
        }
      })
    },
    
    /**
     * 上传头像
     */
    async uploadAvatar(filePath) {
      try {
        uni.showLoading({ title: '上传中...' })
        
        // 这里应该调用上传头像的API
        // const result = await uploadAvatar(filePath)
        // if (result.success) {
        //   this.userInfo.avatarUrl = result.data.avatarUrl
        //   this.showSuccess('头像更新成功')
        // }
        
        // 临时处理
        this.userInfo.avatarUrl = filePath
        this.showSuccess('头像更新成功')
      } catch (error) {
        console.error('上传头像失败:', error)
        this.showError('上传失败')
      } finally {
        uni.hideLoading()
      }
    },
    
    /**
     * 编辑昵称
     */
    editNickname() {
      uni.showModal({
        title: '修改昵称',
        editable: true,
        placeholderText: '请输入新昵称',
        success: async (res) => {
          if (res.confirm && res.content && res.content.trim()) {
            try {
              uni.showLoading({ title: '修改中...' })
              
              const result = await updateUserInfo({
                nickname: res.content.trim()
              })
              
              uni.hideLoading()
              
              if (result && result.success) {
                this.userInfo.nickname = res.content.trim()
                this.showSuccess('昵称修改成功')
                
                // 更新store和缓存
                this.$store.commit('auth/setUserInfo', this.userInfo)
                uni.setStorageSync('userInfo', this.userInfo)
              } else {
                this.showError(result?.message || '修改失败')
              }
            } catch (error) {
              uni.hideLoading()
              console.error('修改昵称失败:', error)
              this.showError('网络错误，修改失败')
            }
          } else if (res.confirm) {
            this.showError('昵称不能为空')
          }
        }
      })
    },
    
    /**
     * 绑定手机号
     */
    bindPhone() {
      this.showTip('手机号绑定功能开发中')
    },
    
    /**
     * 格式化日期
     */
    formatDate(timestamp) {
      if (!timestamp) return '未知'
      const date = new Date(timestamp)
      return date.toLocaleDateString()
    },
    
    /**
     * 显示关于我们
     */
    showAbout() {
      uni.showModal({
        title: '关于我们',
        content: '云打印服务平台\n版本：1.0.0\n为用户提供便捷的打印服务',
        showCancel: false
      })
    },
    
    /**
     * 显示隐私政策
     */
    showPrivacy() {
      this.showTip('隐私政策页面开发中')
    },
    
    /**
     * 退出登录
     */
    logout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除本地存储
            uni.clearStorageSync()
            
            // 跳转到登录页
            uni.reLaunch({
              url: '/pages/auth/login'
            })
          }
        }
      })
    },
    
    /**
     * 页面跳转
     */
    navigateTo(url) {
      if (!url) {
        this.showError('页面路径错误')
        return
      }
      
      uni.navigateTo({
        url,
        fail: (error) => {
          console.error('页面跳转失败:', error)
          this.showError('页面跳转失败')
        }
      })
    },
    
    /**
     * 显示成功提示
     */
    showSuccess(message) {
      uni.showToast({
        title: message,
        icon: 'success',
        duration: 2000
      })
    },
    
    /**
     * 显示错误提示
     */
    showError(message) {
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      })
    },
    
    /**
     * 显示提示
     */
    showTip(message) {
      uni.showModal({
        title: '提示',
        content: message,
        showCancel: false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background: #f5f5f5;
}

// 导航栏样式
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 32rpx;
  padding-top: var(--status-bar-height);
  background: #667eea;
  position: relative;
  z-index: 100;
  box-sizing: border-box;
}

.nav-left {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    opacity: 0.7;
    transform: scale(0.95);
  }
}

.back-icon {
  font-size: 36rpx;
  color: white;
  font-weight: bold;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: white;
}

.nav-right {
  width: 80rpx;
  height: 60rpx;
}

// 用户信息区域
.user-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 40rpx;
  position: relative;
}

.user-avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  border: 4rpx solid #f0f0f0;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  right: 50%;
  transform: translateX(50%);
  background: #667eea;
  color: white;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.user-info {
  .info-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .info-label {
    font-size: 28rpx;
    color: #333;
    width: 160rpx;
  }
  
  .info-value {
    flex: 1;
    font-size: 28rpx;
    color: #666;
  }
  
  .info-arrow {
    font-size: 24rpx;
    color: #999;
  }
}

// 积分信息区域
.points-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 24rpx;
}

.points-grid {
  display: flex;
}

.points-item {
  flex: 1;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
}

.points-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 8rpx;
}

.points-label {
  font-size: 24rpx;
  color: #666;
}

// 菜单区域
.menu-section, .settings-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background: #f8f9fa;
  }
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 24rpx;
}

.menu-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.menu-arrow {
  font-size: 24rpx;
  color: #999;
}
</style>